package idv.arthur.work;

import idv.arthur.work.strucs.S2;
import idv.arthur.work.strucs.S3;
import idv.arthur.work.strucs.ValidateHostStruc1;
import idv.arthur.work.strucs.ValidateHostStruc3;

import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class Widgets {
	
	public final boolean isDebug = false;	//確認目前是否處於Debug模式		
	public final boolean isPrint2Console = false;		//是否要將錯誤訊息，在console上顯示
	public final int ACCESSRIGHT = 0755;	//檔案複制到主機後，上面的權限設定
	
	public final String PROMPT = ">";
	
	public final int CURMAINTAINROLE = 4;	//目前資料庫中負責設定環境的角色
	
	public final String UIcodeSet = "UTF-8";
	public final String APcodeSet = UIcodeSet;
	public final String DBcodeSet = "ISO-8859-1";

	public final int ADD = 1;
	public final int DELETE = 2;
	public final int UPDATE = 3;
	public final int INQUERY = 4;
	
	public final int BSS = 1;
	public final int SUBSYS = 2;
	public final int ENV = 3;		
	public final int SQUAD = 4;
	public final int HOST = 5;	
	public final int PERSONNEL = 6;
	public final int REQUIREMENT=7;
	public final int SQGROUP=8;
	public final int WCL=9;
	
	public final String splitTokenONE = "UUUU";
	public final String splitTokenTWO = "TTTT";
	public final String splitTokenTHREE = "XXXX";
	public final String splitTokenFOUR = "PPPP";
	
	public void keepLogProfile(int profileType,int actionType,String loginUser,Connection conn, PreparedStatement ps ) {
		ResultSet rs= null;
		String errPars =
				toJ("profileType",profileType) +
				toJend("actionType",actionType);
		try {
			ps = conn.prepareStatement("INSERT INTO  log_profile (sn,typeID,type,creator,createdDateTime) VALUES ("+getCurrentSN("log_profile",conn,ps,rs )+",?,?,?,?)");
			ps.setInt(1, profileType);
			ps.setInt(2, actionType);
			ps.setString(3, loginUser);
			ps.setTimestamp(4, currentTimeStamp());
			ps.execute();	
		} catch ( SQLException e) {
			kem(conn, ps, e, toEType("SQLException")+errPars, isPrint2Console );
		} catch ( Exception e) {
			kem(conn, ps, e, toEType("Exception")+errPars, isPrint2Console );
		} finally {
			try {
				if ( rs != null ) { rs.close(); }	
			} catch ( SQLException e ) { System.out.println( errProcess(e) ); }
		}
	}
	
	public String changeTimeFormat(Date dt, String format) {
		return new java.text.SimpleDateFormat(format).format(dt);
	}

	public String changeTimeFormat(Date dt) {
		return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt);
	}
	public String changeTimeFormatUI(Date dt) {
		return new java.text.SimpleDateFormat("yyyy-MM-dd").format(dt)+"<br>"+new java.text.SimpleDateFormat("HH:mm:ss").format(dt);
	}
	
	/**
	 * 	將UI來的字串，其編碼轉成DB的編碼
	 *		創建時間：2013/4/8 下午5:35:45
	 *		創建人員：郭啟揚 (842297)
	 */
	public String UI2DB( String str, String DBType ) throws UnsupportedEncodingException {
		if ( "MySQL".equalsIgnoreCase(DBType) ) {
			return str;
		} else {
			return ( new String( str.getBytes( UIcodeSet ), DBcodeSet ) );	
		}
	}
	
	/**
	 * 	將DB來的字串，其編碼轉成UI的編碼
	 *		創建時間：2013/4/8 下午5:36:48
	 *		創建人員：郭啟揚 (842297)
	 */
	public String DB2UI( String str, String DBType ) throws UnsupportedEncodingException {
		if ( "MySQL".equalsIgnoreCase(DBType) ) {
			return str;
		} else {
			return ( new String( str.getBytes( DBcodeSet ), UIcodeSet ) );	
		}
		
	}
	
	
	public String getTarSVNConnection(int fromSysNo,int tarSysNo,Connection conn, PreparedStatement ps, ResultSet rs,String split) {
		String res = "";
		String strSQL = "SELECT svnLoginSN FROM mpsyssvn WHERE fromSysSN = ? AND tarSysSN = ?";
		
		try {
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, fromSysNo);
			ps.setInt(2, tarSysNo);
			rs = ps.executeQuery();
			rs.next();
			
			int svnLoginSN = rs.getInt("svnLoginSN");
			rs.close();
			
			strSQL = "SELECT loginURL, id, pwd FROM svnlogin WHERE svnLoginSN=?";
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, svnLoginSN);
			rs = ps.executeQuery();
			rs.next();
			
			res=rs.getString("id")+split+rs.getString("pwd")+split+rs.getString("loginURL");
			
		} catch (SQLException x) {
			System.out.println(errProcess(x));
		} catch (Exception e) {
			System.out.println(errProcess(e));
		}
		
		return res;
	}
	
	
	public String toEType(String exceptionType) {
		return "{\"ExcepType\":\""+exceptionType+"\"";	
	}
	public String toETypeEnd(String exceptionType) {
		return "{\"ExcepType\":\""+exceptionType+"\"";	
	}
	
	public String toJ(String parName,String parVal) {
		return ",\""+parName+"\":\""+parVal+"\"";
	}
	public String toJend(String parName,String parVal) {
		return toJ(parName,parVal) + "}";
	}
	public String toJ(String parName,long parVal) {
		return ",\""+parName+"\":\""+parVal+"\"";
	}
	public String toJend(String parName,long parVal) {
		return toJ(parName,parVal) + "}";
	}
	public String toJ(String parName,int parVal) {
		return ",\""+parName+"\":\""+parVal+"\"";
	}
	public String toJend(String parName,int parVal) {
		return toJ(parName,parVal) + "}";
	}
	
	public Connection getTarConnection(int fromSysNo,int tarSysNo,Connection conn, PreparedStatement ps, ResultSet rs) throws SQLException, ClassNotFoundException,Exception {
		Connection tarConn = null;
		String strSQL = "SELECT dbLoginSN FROM mpsysdb WHERE fromSysSN=? AND tarSysSN=?";
		String url = null;
		
		ps = conn.prepareStatement(strSQL);
		ps.setInt(1, fromSysNo);
		ps.setInt(2, tarSysNo);
		rs = ps.executeQuery();
		rs.next();
		
		int dbLoginSN = rs.getInt("dbLoginSN");
		
		strSQL = "SELECT t1.dbName,t2.dbtypename, t1.ip, t1.port, t1.id, t1.pwd,t2.strProtocol FROM dblogin t1, dbtype t2 WHERE t1.DBTypeSN = t2.DBTypeSN AND t1.dbLoginSN=?";
		ps = conn.prepareStatement(strSQL);
		ps.setInt(1, dbLoginSN);
		rs = ps.executeQuery();
		rs.next();
		if ( rs.getString("dbtypename").contains( "MySQL" ) ) {
			Class.forName("com.mysql.jdbc.Driver");
		} else if ( rs.getString("dbtypename").contains( "Informix" ) ) {
			Class.forName("weblogic.jdbc.informix.InformixDriver");	//weblogic上的class
			//Class.forName("com.informix.jdbc.IfxDriver");		//部門內常用的ifxjdbc
			//strProtocol  --> jdbc:informix-sqli 部門內常用的ifxjdbc
			//strProtocol  --> jdbc:weblogic:informix weblogic上的class
			//url = rs.getString("strProtocol")+"://"+rs.getString("ip")+":"+rs.getInt("port")+"/"+rs.getString("dbName")+":informixServer=qaserver;NEWCODESET=UTF-8,big5,8859-1,819;IFX_USE_STRENC=true";
			url = "jdbc:weblogic:informix://"+rs.getString("ip")+":"+rs.getInt("port")+";DatabaseName="+rs.getString("dbName")+";informixServer=qaserver;NEWCODESET=UTF-8,big5,8859-1,819;IFX_USE_STRENC=true";
			tarConn = DriverManager.getConnection( url,rs.getString("id"),rs.getString("pwd") );	
		}
		
		return tarConn;
	}
	
	public Connection getConn(boolean isWeb) {
		Connection conn = null;

		if (isWeb) {
			try {
				Context ctx = new InitialContext();
				DataSource ds = (DataSource) ctx.lookup("java.env.jdbc.DPS");
				//DataSource ds = (DataSource) ctx.lookup("java:/env/jdbc/DPS");
				conn = ds.getConnection();
			} catch (NamingException e) {
				System.out.println("å»ºç«é£ç·æç¼çé¯èª¤" + e.toString());
			} catch (SQLException e) {
				System.out.println("å»ºç«é£ç·æç¼çé¯èª¤" + e.toString());
			}
		} else {
			try {
				Class.forName("com.mysql.jdbc.Driver");
				conn = DriverManager.getConnection("jdbc:mysql://10.144.136.54:3306/dpsTar01", "p_dpstar01","p_dpstar011234");
			} catch (ClassNotFoundException e) {
				System.out.println( errProcess(e) );
			} catch (SQLException x) {
				System.out.println( errProcess(x) );
			} catch (Exception e) {
				System.out.println( errProcess(e) );
			}
		}
		return conn;
	}
	
	public Timestamp currentTimeStamp(String format){
		java.util.Date dt = new java.util.Date();
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
	    String currentTime = sdf.format(dt);
	    return Timestamp.valueOf(currentTime);
	}
	
	public Timestamp currentTimeStamp(){
		java.util.Date dt = new java.util.Date();
	    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String currentTime = sdf.format(dt);
	    return Timestamp.valueOf(currentTime);
	}
	
	/*	將errorMessage 改成我想看的格式字串	*/
	public String errProcess (Exception e) {
		String mes = e.toString() + "\n\n";
		for (int i=0; i<e.getStackTrace().length;i++) {
			mes += "File Name:\t"+e.getStackTrace()[i].getFileName() + "\n";
			mes += "Line Number:\t"+e.getStackTrace()[i].getLineNumber() + "\n\n";
		}
		return mes;
	}
	
	public int getCurrentSN(String table,Connection conn, PreparedStatement ps,ResultSet rs ) {
		
		String strSQL = "UPDATE envtable_seq SET seqcurrent = (seqcurrent + 1) WHERE seqname=?";
		String errPars = toJend("seqname",table);
		int res = 0;
		try {
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, table);
			ps.execute();
			
			strSQL = "SELECT seqcurrent FROM envtable_seq WHERE seqname=?";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, table);
			rs = ps.executeQuery();
			rs.next();
			res = rs.getInt(1);
		} catch ( SQLException e) {
			kem(conn, ps, e, toEType("SQLException")+errPars, isPrint2Console );
		} catch ( Exception e) {
			kem(conn, ps, e, toEType("Exception")+errPars, isPrint2Console );
		} 
		return res;
	}
	
	public int getLocalSysNo(Connection conn, PreparedStatement ps,ResultSet rs ) {
		String strSQL = "SELECT sysSN FROM envsystemlist WHERE isLocalSys='t'";
		int res =0;
		try {
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			rs.next();
			res =rs.getInt(1);
		} catch ( SQLException e) {
			kem(conn, ps, e, toETypeEnd("SQLException"), true);
		} catch ( Exception e) {
			kem(conn, ps, e, toETypeEnd("Exception"), true);
		} 
		
		return res;
	}
	
	public String getLocalSysName(Connection conn, PreparedStatement ps,ResultSet rs ) throws SQLException, UnsupportedEncodingException {
		String str = "SELECT sysname FROM envsystemlist WHERE isLocalSys='t'";
		ps = conn.prepareStatement(str);
		rs = ps.executeQuery();
		rs.next();
		
		return new String( rs.getString(1).getBytes( DBcodeSet ), UIcodeSet);
	}
	
	/**
	 *		用來追蹤Bug用的函式，將欲補捉的參數寫入DB中
	 *		創建時間：2013/5/15 上午9:15:23<br>
	 *		創建人員：郭啟揚 (842297)
	 */
	public void bugTrace (Connection conn, PreparedStatement ps,String mes, String para) {
		ResultSet rs= null;
		try {
			ps = conn.prepareStatement("INSERT INTO errmes (errMesSN,errMes,des) VALUES ("+getCurrentSN("errmes", conn, ps, rs)+",?,?)");
			ps.setString(1, mes);
			ps.setString(2, para);
			ps.execute();
		} catch (SQLException e1) {
			System.out.println( errProcess(e1) );
		} finally {
			try {
				if ( rs != null ) { rs.close(); }	
			} catch ( SQLException e ) { System.out.println( errProcess(e) ); }
		}
	}
	
	public String kem (Connection conn, PreparedStatement ps,Exception e, String des, boolean isDisplay) {
		
		String mes = errProcess(e);
		
		if ( isDisplay ){ System.out.print(mes);}
		ResultSet rs= null;
		try {
			ps = conn.prepareStatement("INSERT INTO errmes (errMesSN,errMes,des) VALUES ("+getCurrentSN("errmes", conn, ps, rs)+",?,?)");
			ps.setString(1, UI2DB(mes,conn.getMetaData().getDatabaseProductName()));
			ps.setString(2, des);
			ps.execute();
		} catch (SQLException e1) {
			System.out.println( errProcess(e1) );
		} catch ( UnsupportedEncodingException e1) {
			System.out.println( errProcess(e1) );
		} finally {
			try {
				if ( rs != null ) { rs.close(); }	
			} catch ( SQLException e1 ) { System.out.println( errProcess(e1) ); }
		}
		return mes;
	}
	
	/**
	 *		確認每個資源群組下
	 *			1. 都有存在主機，
	 *			2.	該主機所維護的帳密是可以登入
	 *			3.	能切換至部署路徑 (2013/06/20 18:29)
	 *
	 *		創建時間：2013/5/9 上午10:35:51<br>
	 *		創建人員：郭啟揚 (842297)
	 */
public ValidateHostStruc3 valiEnvHost( Connection conn, PreparedStatement ps,ResultSet rs,String bssId,String subSysId,String envId,String pars, boolean isCheckLoginId )  {
		
		ValidateHostStruc3 vhses = new ValidateHostStruc3();
		ArrayList<ValidateHostStruc1> vses2 = new ArrayList<ValidateHostStruc1>();		//記錄那些Squad出問題
		ArrayList<S2> squadsWithNoHost = new ArrayList<S2>();	//沒有設定主機的 Squad列表
		String strSQL = null;
		String errPars = "{";
		
		final String[] sqs = pars.split(splitTokenONE);
		String hsList = "";
		PreparedStatement ps2 = null;
		
		boolean allSquWithHost = true;	//所有的SQUAD都有設定主機
		boolean loginOK = true;					//所有的主機都能登入
		boolean pathExist = true;				//部署路徑都是存在的
		boolean pathAccessOK = true;					//皆能切換到指定的部署路徑
		
		
		try {
			if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
				strSQL = "SELECT mpsquadhosts.bssid as 'i', hosts.port,hosts.ip,hosts.hostname,hosts.loginId,hosts.loginPWD FROM hosts LEFT JOIN mpsquadhosts ON hosts.bssid=mpsquadhosts.bssid AND hosts.subsysid=mpsquadhosts.subsysid AND hosts.ip=mpsquadhosts.ip AND hosts.port=mpsquadhosts.port AND mpsquadhosts.envid=?  AND mpsquadhosts.squadid=? WHERE hosts.bssid=? AND hosts.subsysid=?";	
			} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
				strSQL = "SELECT t1.port,t3.squadpath,t1.ip,t1.hostname,t1.loginId,t1.loginPWD FROM mpsquadhosts t2,hosts t1,squad t3 WHERE  t3.squadid=t2.squadid AND t3.bssid=t2.bssid AND t3.subsysid=t2.subsysid AND t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.ip=t2.ip AND t1.port=t2.port AND t2.envid=?  AND t2.squadid=? AND t1.bssid=? AND t1.subsysid=?";
			}
			ps = conn.prepareStatement( strSQL );
			
			for (int i=0; i < sqs.length; i++ ) {
				ps.setString(1, envId);
				ps.setString(2, sqs[i]);
				ps.setString(3, bssId);
				ps.setString(4, subSysId);
				errPars = toJ("envid",envId) + toJ("squadid", sqs[i]) + toJ("bssid", bssId) + toJend("subsysid", subSysId);
				
				rs = ps.executeQuery();
				boolean isHostNotExisted = true;		//先預設這個 SQUAD沒有設定主機
				
				ArrayList<S3> hostCantLogin = new ArrayList<S3>();				//無法登入的主機
				ArrayList<S3> pathNotExist = new ArrayList<S3>();					//欲切換至的部署路徑不存在
				ArrayList<S3> pathCantAccess = new ArrayList<S3>();				//無法切換至切換至的部署路徑
				hsList += ( splitTokenTHREE + sqs[i] + splitTokenFOUR );
				
				if ( rs.next() ) {	//表示有設定主機
					isHostNotExisted = false;
					rs = ps.executeQuery();	
					while ( rs.next() ) {
						int result = 0;
						hsList += ( splitTokenTWO+rs.getString("ip")+splitTokenONE+ rs.getInt("port")+splitTokenONE+ DB2UI( rs.getString("hostname"),conn.getMetaData().getDatabaseProductName() ) );
						result = testConnection(conn,ps,rs.getString("ip"),rs.getString("loginId"),rs.getString("loginPWD"),rs.getString("squadpath") );	//一台台主機檢查(因為while loop) 能否登入，切換路徑
						S3 lao = new S3();
						lao.setA( DB2UI( rs.getString("hostname"),conn.getMetaData().getDatabaseProductName() ) );
						lao.setB( rs.getString("ip") );				
						lao.setC( rs.getString("loginId") );
						if ( result == 0 ) {	//無法登入
							hostCantLogin.add( lao );
							loginOK = false;
						} else if ( result == 2 ) {	//可以登入，但欲切換至的部署路徑不存在
							pathNotExist.add(lao);
							pathExist = false;
						} else if ( result == 3 ) {	//可以登入，但無法切換至的欲前往的部署路徑
							pathCantAccess.add(lao);
							pathAccessOK = false;
						}
						
					}
				} else{
					allSquWithHost = false;
				}
				
				strSQL ="SELECT squadname FROM squad WHERE bssid=? AND subsysid=? AND squadid=?";
				ps2 = conn.prepareStatement(strSQL);
				ps2.setString(1, bssId);
				ps2.setString(2, subSysId);
				ps2.setString(3, sqs[i]);
				errPars = toJ("bssid", bssId) + toJ("subsysid", subSysId) + toJend("squadid",sqs[i] );
				
				rs = ps2.executeQuery();
				if ( rs.next() ) {
					if ( isHostNotExisted ) {	//沒有設定主機
						S2 squadWithNoHost = new S2();
						squadWithNoHost.setA( sqs[i] );
						squadWithNoHost.setB( rs.getString("squadname") );
						squadsWithNoHost.add( squadWithNoHost );
					} else {
						
						if ( hostCantLogin.size() ==0 &&  pathNotExist.size() == 0 && pathCantAccess.size() == 0 ) {	//都沒有問題
							vhses.setHsList(hsList.substring(splitTokenTHREE.length(), hsList.length()));							
						} else {
							ValidateHostStruc1 v1 = new ValidateHostStruc1();									//這個出問題的Squad
							v1.setSquadName( DB2UI( rs.getString("squadname"),conn.getMetaData().getDatabaseProductName() ) );
							v1.setRes(sqs[i]);
							if ( hostCantLogin.size() > 0 ) {		//存在無法登入的主機
								v1.setHostCantLogin(hostCantLogin);
							}
							if ( pathNotExist.size() > 0 ) {			//存在欲切換至的部署路徑不存在
								v1.setPathNotExist( pathNotExist );
							}
							if ( pathCantAccess.size() > 0 ) {		//無法切換至切換至的部署路徑存在無法登入的主機
								v1.setPathCantAccess( pathCantAccess );
							}
							vses2.add(v1);
						}
					}
				}
			}
			
			vhses.setSquadsWithNoHost( squadsWithNoHost );
			vhses.setV2(vses2);
			
			vhses.setRes( (allSquWithHost?"1":"0")+(loginOK?"1":"0")+(pathExist?"1":"0")+(pathAccessOK?"1":"0")  );
			
			
		} catch ( SQLException e ) {
			kem(conn, ps, e, toEType("SQLException")+errPars, isPrint2Console );
		} catch ( UnsupportedEncodingException e ) {
			kem(conn, ps, e, toEType("UnsupportedEncodingException")+errPars, isPrint2Console );
		} catch ( Exception e ) {
			kem(conn, ps, e, toEType("Exception")+errPars, isPrint2Console );
		} finally {
			try {
				if ( ps2 != null ) { ps2.close(); }
			} catch (SQLException e) {
				kem(conn, ps, e, toEType("SQLException"), true);
			}
		}
		
		return vhses;
	}
	
	/**
	 *		@param res 檢查結果值
	 *			<br>0 不可登入
	 *			<br>1 可登入，可切換
	 *			<br>2 可登入，但無法切換至 "不存在的"部署路徑
	 *			<br>3 可登入，但無法切換至 "不具權限存取的"部署路徑
	 *		創建時間：2013/6/21 上午9:26:31<br>
	 *		創建人員：郭啟揚 (842297)
	 */
	public int testConnection(Connection conn,PreparedStatement ps,String ip,String loginId,String pwd,String squadpath)  {
		int res = 0;
		String errPars =
				toJ("loginId",loginId) +
				toJend("pwd",pwd);
		
        Session session = null;
        try {
        	JSch jsch = new JSch();
            JSch.setConfig("StrictHostKeyChecking", "no");
        	session = jsch.getSession(loginId, ip);
        	session.setPassword(pwd);
            session.setTimeout(5000);
            session.connect();
            ChannelSftp sftp = (ChannelSftp)  session.openChannel("sftp");
            sftp.connect();
            res = 1;	// 可登入，可切換
            try {
            	if ( !squadpath.startsWith("/") ) {	//檢查暨有部署路徑的開頭是否為 / 開頭，若無就加上去
            		squadpath = "/"+squadpath;  
            	}
        		sftp.cd( squadpath );
        		sftp.ls( squadpath );
        	} catch (SftpException e) {
        		if ( e.toString().contains("No such file") ) {
        			res = 2;	//表示 可登入但無法切換至 "不存在的"部署路徑
        		} else if ( e.toString().contains("Permission denied") ) {
        			res = 3;	//表示 無法切換至 "不具權限存取的"部署路徑
        		}
        	}
        } catch (JSchException e) {
        	if ( !e.toString().contains("Auth fail") ) {
        		kem(conn, ps, e, toEType("JSchException")+errPars, isPrint2Console );
        	} else {
        		return res;
        	}
        } finally {
        	if ( session != null ) {
    			if ( session.isConnected() ) {
    				session.disconnect();
    			} 	
    		}	
        }
        return res;
	}
	
	public boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			int chr = str.charAt(i);
			if (chr < 48 || chr > 57)
				return false;
		}
		return true;
	}
	
	 public String sendCommand(String command, InputStream input,PrintStream out) {
	        try {
	            write(command,out);
	            return readUntil(PROMPT + " ", input);
	        } catch (Exception e) {
	        	System.out.println( errProcess(e) );
	        }
	        return null;
	    }
	
	//組合部署指令
    public String composeCommand(String deployIP, String account, String password, String modulename,
                                 String modulenameWithExt, String deployTargets, String action){

        String ret = "";

        if(action.equals("deploy")){
            ret = "java weblogic.Deployer"
                  + " -adminurl t3://" + deployIP + ":8080"
                  + " -username " + account
                  + " -password " + password
                  + " -name " + modulename
                  + " -source " + modulenameWithExt
                  + " -targets " + deployTargets
                  + " -deploy";
        }

        if(action.equals("undeploy")){
            ret = "java weblogic.Deployer"
                  + " -adminurl t3://" + deployIP + ":8080"
                  + " -username " + account
                  + " -password " + password
                  + " -name " + modulename
                  + " -targets " + deployTargets
                  + " -undeploy";
        }

        if(action.equals("redeploy")){
            ret = "java weblogic.Deployer"
                  + " -adminurl t3://" + deployIP + ":8080"
                  + " -username " + account
                  + " -password " + password
                  + " -name " + modulename
                  + " -targets " + deployTargets
                  + " -redeploy";
        }
        return ret;
    }
    
    public void cwd (ChannelSftp sftp, String path) throws SftpException { 
		String[] hie  = path.split("/");
		for(int i=0; i<hie.length;i++) {
			if ("".equalsIgnoreCase(hie[i])) {continue;}
			try {
				sftp.cd(hie[i]);
			} catch (SftpException e) {
				sftp.mkdir(hie[i]);
				sftp.chmod( ACCESSRIGHT,hie[i]);
				sftp.cd(hie[i]);
			}
		}
	}
	
	public String readUntil( String pattern, InputStream input ) {
        try {
            char lastChar = pattern.charAt(pattern.length() - 1);
            StringBuffer sb = new StringBuffer();
            char ch = (char) input.read();  //read(): 不需要傳任何參數，一次讀取一個 byte data，並以 int 型態傳回資料。若無任何資料可讀，則回傳 -1。
            while (true) {
                System.out.print(ch);
                sb.append(ch);
                if (ch == lastChar) {
                    if ( sb.toString().endsWith(pattern) ) {
                        return sb.toString();
                    }
                }
                ch = (char) input.read();
            }
        } catch (Exception e) {
        	System.out.println( errProcess(e) );
        }
        return null;
    }

    public void write(String value, PrintStream out) {
        try {
            out.println(value);
            out.flush();
            System.out.println(value);
        } catch (Exception e) {
        	System.out.println( errProcess(e) );
        }
    }

	
  //處理部署訊息
    public String deployInfo(String msg){

        if(msg.contains(" redeploy completed ") ){
        	return "Redeploy successfully.";
        } else{ return msg; }
    }
}
